//
//  LauNewFeatureView.swift
//  SwiftProject
//
//  Created by Lausen on 2017/8/17.
//  Copyright © 2017年 id. All rights reserved.
//

import UIKit

/// 新特性界面的自定义视图
class LauNewFeatureView: UIView {
    
    /// 进入微博的按钮
    @IBOutlet weak var button: UIButton!
    /// 分页空间
    @IBOutlet weak var pageControl: UIPageControl!
    /// 滚动视图
    @IBOutlet weak var scrollView: UIScrollView!
    
    // MARK: --  返回新特性的类方法
    class func newFeatureView() -> LauNewFeatureView{
        
        let nib = UINib(nibName: "LauNewFeatureView", bundle: Bundle.main)
        
        let v = nib.instantiate(withOwner: nil, options: nil)[0] as! LauNewFeatureView
        
        v.frame = UIScreen.main.bounds
        
        return v
    }
    
    // MARK: --  通过xib加载视图时调用的方法
    override func awakeFromNib() {
        super.awakeFromNib()
        
        let count = 4
        let rect = UIScreen.main.bounds
        
        // 利用for循环,将图片视图添加到滚动视图上
        for i in 0..<count {
            
            let iv = UIImageView()
            
            let imageName = "new_feature_\(i + 1)"
            
            iv.image = UIImage(named: imageName)
            
            iv.frame = rect.offsetBy(dx: CGFloat(i) * rect.width, dy: 0)
            
            scrollView.addSubview(iv)
        }
        
        //设置scrollView的属性
        scrollView.contentSize = CGSize(width: CGFloat(count + 1) * rect.width, height: rect.height)
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.bounces = false
        scrollView.isPagingEnabled = true
        
        //设置按钮的隐藏
        button.isHidden = true
        
        //设置scrollView的代理
        scrollView.delegate = self
        
        //设置分页空间的不可交互
        pageControl.isUserInteractionEnabled = false
    }
    
    // MARK: --  进入微博的按钮点击时间
    @IBAction func enterStatus(_ sender: UIButton) {
        
        //移除父视图
        removeFromSuperview()
    }
}

// MARK: --  scrollView的代理方法
extension LauNewFeatureView: UIScrollViewDelegate{
    
    // MARK: --  滑动结束时调用的方法
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        
        //根据偏移量来计算当前的页数
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width) + 1
        
        //当当前的界面不等于第四页的时候,就隐藏"进入微博"的按钮
        button.isHidden = (page != scrollView.subviews.count - 1)
        
        //如果是最后一页,直接移除
        if page == scrollView.subviews.count {
            
            removeFromSuperview()
        }
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
       
        //视图一旦滚动,就让按钮隐藏
        button.isHidden = true
        
        //当页面滑动过一半的时候,就算是滚动了一个界面
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width + 0.5)
        
        //设置分页空间的当前页
        pageControl.currentPage = page
        
        //隐藏分页空间
        pageControl.isHidden = (page == scrollView.subviews.count - 1)
    }
}








